package com.cpip.user.controller;

import com.alibaba.fastjson.JSON;
import com.cpip.common.pojo.Admin;
import com.cpip.common.vo.DataResponse;
import com.cpip.user.config.JwtUtil;
import com.cpip.user.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/admin")
@CrossOrigin
public class AdminController {
    @Autowired
    AdminService adminService;
    @Autowired
    private JwtUtil jwtUtil;

    //解析token
    @GetMapping("/getInformationFromToken")
    public DataResponse getToken(@RequestParam String token) {
        String jsonInformation = jwtUtil.getInformationFromToken(token);
        Admin admin = JSON.parseObject(jsonInformation, Admin.class);
        if (admin != null) {
            return DataResponse.success(admin);
        } else {
            return DataResponse.error("解析失败");
        }
    }

    //登录校验
    @PostMapping("/login")
    public DataResponse login(@RequestBody Admin admin) {
        Admin adminLogin = adminService.login(admin.getAccount(), admin.getAdminPassword());
        if (adminLogin == null) {
            return DataResponse.error("登录失败");
        }
        //生成令牌
        String jsonInformation = JSON.toJSONString(adminLogin);
        String token = jwtUtil.generateToken(jsonInformation);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("account", adminLogin.getAccount());
        return DataResponse.success(map);
    }

    //修改
    @PutMapping("/update")
    public DataResponse update(@RequestBody Admin admin) {
        try {
            adminService.update(admin);
            return DataResponse.success();
        } catch (Exception e) {
            e.printStackTrace();
            return DataResponse.error("修改失败");
        }
    }
}
